import threading
import time
from typing import Callable, List, Dict


class TimerTask:
    def __init__(self, interval: int, callback: Callable, args: List = None, kwargs: Dict = None,
                 auto_start: bool = True):
        self.interval = interval  # 执行间隔(秒)
        self.callback = callback  # 回调函数
        self.args = args or []  # 位置参数
        self.kwargs = kwargs or {}  # 关键字参数
        self.running = False  # 运行状态
        self._timer = None  # 定时器对象
        self.next_run_time = None  # 下次运行时间

        if auto_start:
            self.start()

    def _run(self):
        """定时执行的内部方法"""
        self.running = False
        self.start()  # 重新启动定时器
        try:
            self.callback(*self.args, **self.kwargs)
        except Exception as e:
            print(f"定时器任务执行出错: {e}")

    def start(self):
        """启动定时器"""
        if not self.running:
            self.running = True
            self.next_run_time = time.time() + self.interval
            self._timer = threading.Timer(self.interval, self._run)
            self._timer.daemon = True
            self._timer.start()

    def stop(self):
        """停止定时器"""
        if self.running and self._timer:
            self._timer.cancel()
            self.running = False

    def get_status(self):
        """获取定时器状态"""
        return {
            "running": self.running,
            "interval": self.interval,
            "next_run_time": self.next_run_time,
            "callback": self.callback.__name__ if callable(self.callback) else str(self.callback)
        }